import FileImageOutlined from "@ant-design/icons/FileImageOutlined"
import { Product } from "@mallfoundry/catalog"
import { Col, Row } from "antd"
import BraftEditor, { ControlType, EditorState, ExtendControlType } from "braft-editor"
import "braft-editor/dist/index.css"
// @ts-ignore
import { ContentUtils } from "braft-utils"
import * as _ from "lodash"
import * as React from "react"
import { useEffect, useState } from "react"
import { ImageBlobsModal } from "../store/blobs/image-blobs"
import classes from "./product-body.module.scss"

interface ProductBodyProps {
  product: Product
}

export default function ProductBody(props: ProductBodyProps) {

  const controls: ControlType[] = [
    "undo", "redo", "separator",
    "font-size", "line-height", "letter-spacing", "separator",
    "text-color", "bold", "italic", "underline", "strike-through", "separator",
    "superscript", "subscript", "remove-styles", "emoji", "separator", "text-indent", "text-align", "separator",
    "headings", "list-ul", "list-ol", "blockquote", "code", "separator",
    "link", "separator", "hr", "separator", "clear",
  ]

  const [imageBlobsModalVisible, setImageBlobsModalVisible] = useState(false)

  const extendControls: ExtendControlType[] = [
    {
      key: "image-button",
      type: "button",
      text: <FileImageOutlined/>,
      onClick: () => {
        setImageBlobsModalVisible(true)
      },
    },
  ]

  const { product } = props
  const [editorState, setEditorState] = useState(BraftEditor.createEditorState(product.body))

  useEffect(() => {
    setEditorState(BraftEditor.createEditorState(product.body))
  }, [product.body])

  function handleChange(editorState: EditorState) {
    product.body = editorState.toHTML()
    setEditorState(editorState)
  }

  return (
    <div className={classes.productBody}>
      <ImageBlobsModal visible={imageBlobsModalVisible} selectable
                       onSelect={blobs => {
                         const medias = _.map(blobs, blob => ({
                           type: "IMAGE",
                           url: blob.url,
                         }))
                         const newEditorState = ContentUtils.insertMedias(editorState, medias)
                         setEditorState(newEditorState)
                         setImageBlobsModalVisible(false)
                       }}
                       onCancel={() => setImageBlobsModalVisible(false)}/>
      <Row>
        <Col offset={9} span={6}>
          <BraftEditor className={classes.productBodyBraft}
                       controls={controls} extendControls={extendControls}
                       value={editorState} onChange={handleChange}/>
        </Col>
      </Row>
    </div>
  )
}
